﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ResumeVideo
{
    [Serializable()]
    public class MovieList
    {
        private List<Movie> _movies = new List<Movie>();
        public List<Movie> Movies
        {
            get { return _movies; }
            set { _movies = value; }
        }

        public void Save(string Path)
        {
            TextWriter tw = null;
            try
            {
                XmlSerializer xml = new XmlSerializer(typeof(List<Movie>));
                tw = new StreamWriter(Path);
                xml.Serialize(tw, Movies);
            }
            catch { }
            finally
            {
                if (tw != null)
                    tw.Close();
            }
        }

        public void Load(string Path)
        {
            FileStream fs = null;
            try
            {
                if (File.Exists(Path))
                {
                    XmlSerializer xml = new XmlSerializer(typeof(List<Movie>));
                    fs = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read);
                    Movies = (List<Movie>)xml.Deserialize(fs);
                }
            }
            catch { }
            finally
            {
                if (fs != null)
                    fs.Close();
            }

        }

        public void SetLastPosition(string path, int lastPosition, string computer)
        {
            Movie currentMovie = new Movie { Path = path, LastComputer = computer, LastPosition = lastPosition };
            SetLastPosition(currentMovie);
        }

        public void SetLastPosition(Movie movie)
        {
            var lastMovie = from m in Movies
                            where m.Path == movie.Path
                            select m;

            if (lastMovie != null)
            {
                if (lastMovie.Count() == 1)
                {
                    lastMovie.First().LastPosition = movie.LastPosition;
                    lastMovie.First().LastComputer = movie.LastComputer;
                }
                else
                {
                    var lastMovies = (from m in Movies
                                      where m.Path == movie.Path
                                         && m.LastComputer == movie.LastComputer
                                      select m).FirstOrDefault();
                    if (lastMovies != null)
                    {
                        lastMovies.LastPosition = movie.LastPosition;
                        lastMovies.LastComputer = movie.LastComputer;
                    }
                    else
                    {
                        Movies.Add(movie);
                    }
                }
            }

        }
    }
}
